package com.media.appmedia.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.media.appmedia.R;
import com.media.appmedia.appupdata.NewVersion;
import com.media.appmedia.baiduutils.BaiduLocationManager;
import com.media.appmedia.baiduutils.BaiduLocationManager.LocationStrAddCallBack;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.contarl.FragmentTabAdapter;
import com.media.appmedia.contarl.FragmentTabAdapter.OnRgsExtraCheckedChangedListener;
import com.media.appmedia.fragment.Exchange_Fragment;
import com.media.appmedia.fragment.Make_Money_Fragment;
import com.media.appmedia.fragment.MyFragement;
import com.media.appmedia.fragment.Setting_Fragment;
import com.media.appmedia.network.ProtocolConst;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.slidingmenu.AccountActivity;
import com.media.appmedia.slidingmenu.GeneralizeActivity;
import com.media.appmedia.slidingmenu.IntegralActivity;
import com.media.appmedia.slidingmenu.MyActivity;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.slidingmenu.lib.SlidingMenu;

/**
 * 
 * <pre>
 * 业务名:
 * 功能说明:  主界面，实现自动轮播，左侧滑，跳转，fragment替换
 * 编写日期:	2014-10-22
 * 作者:	 Rose
 * 
 * 历史记录
 * 1、修改日期：
 *    修改人：Rose
 *    修改内容：主activity瘦身，转移至Myfragment中！
 * </pre>
 */
public class MainActivity extends FragmentActivity {
	// 更新使用
	private String downloadPath = ProtocolConst.VERSION_DOWLOAC;
	private String appVsrsion = "android_version.json";
	private Context mContext;
	private SlidingMenu slidingMenu;
	private RadioGroup mradiogroup;
	private static Boolean isExit = false;
	private RadioButton mMy, mIntegral, mGeneralize, mAccount;
	private ArrayList<Fragment> listFragments;
	private FragmentTabAdapter fragmentTabAdapter;
	private LinearLayout layout;

	// 定位功能
	private BaiduLocationManager manager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.main);
		BaseApplication.getApplication().setListAct(this);
		layout = (LinearLayout) findViewById(R.id.linear_red);
		mContext = this;
		// 版本更新
		getVersion(this);
		// 定位
		locading();
		// 我的页面
		listFragments = new ArrayList<Fragment>();
		listFragments.add(new MyFragement());
		listFragments.add(new Make_Money_Fragment());// 赚钱页面
		listFragments.add(new Exchange_Fragment());// 兑换页面
		listFragments.add(new Setting_Fragment());// 设置页面
		mradiogroup = (RadioGroup) findViewById(R.id.RadioGroupMain);
		fragmentTabAdapter = new FragmentTabAdapter(
				getSupportFragmentManager(), listFragments,
				R.id.contentfragmemt, mradiogroup);
		fragmentTabAdapter
				.setOnRgsExtraCheckedChangedListener(new OnRgsExtraCheckedChangedListener() {

					@Override
					public void OnRgsExtraCheckedChanged(RadioGroup radioGroup,
							int checkedId, int index) {
						for (int i = 0; i < 4; i++) {
							ImageView imageView = (ImageView) layout
									.getChildAt(i);
							imageView.setImageResource(R.color.white);
						}
						ImageView imageView = (ImageView) layout
								.getChildAt(index);
						imageView.setImageResource(R.drawable.tabred);

					}
				});
		BaseApplication.getApplication().setFragmentTabAdapter(
				fragmentTabAdapter);

		slidingMenu();
		BaseApplication.getApplication().setmSlidingMenu(slidingMenu);
		BaseApplication.getApplication().startLockService();
	}

	/**
	 * 
	 * 方法说明：实现侧滑功能
	 * 
	 */
	private void slidingMenu() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		slidingMenu.setBehindWidth(160);
		slidingMenu.setFadeDegree(0.35f);
		slidingMenu.setMode(SlidingMenu.LEFT);
		slidingMenu.setMenu(R.layout.slidingmenu);
		slidingMenu.attachToActivity(this, SlidingMenu.TOUCHMODE_FULLSCREEN);
		slidingMenu.setShadowWidth(screenWidth / 20);

		slidingMenu.setBehindOffset(screenWidth / 2);
		slidingMenu.setFadeEnabled(true);
		slidingMenu.setBehindScrollScale(0);
		mMy = (RadioButton) findViewById(R.id.Myx);
		mIntegral = (RadioButton) findViewById(R.id.integral);
		mGeneralize = (RadioButton) findViewById(R.id.Generalize);
		mAccount = (RadioButton) findViewById(R.id.Account);

		mMy.setOnClickListener(onClick);
		mIntegral.setOnClickListener(onClick);
		mGeneralize.setOnClickListener(onClick);
		mAccount.setOnClickListener(onClick);

	}

	OnClickListener onClick = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			// 我的信息
			case R.id.Myx:
				Intent intentMy = new Intent(mContext, MyActivity.class);
				MainActivity.this.startActivity(intentMy);
				break;
			// 明细跳转
			case R.id.integral:
				Intent intentIntegral = new Intent(mContext,
						IntegralActivity.class);
				MainActivity.this.startActivity(intentIntegral);
				break;
			// 邀请好友列表
			case R.id.Generalize:
				Intent intentGeneralize = new Intent(mContext,
						GeneralizeActivity.class);
				startActivity(intentGeneralize);
				break;
			// 账号信息
			case R.id.Account:
				Intent intentAccoun = new Intent(mContext,
						AccountActivity.class);
				startActivity(intentAccoun);
				break;
			}
		}
	};

	/**
	 * 实现一键退出功能
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isExit == false) {
				AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(
						MainActivity.this);
				alertbBuilder
						.setTitle("提示")
						.setMessage("确认退出应用吗？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// 结束这个Activity
										MainActivity.this.finish();
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();

									}
								}).create();
				alertbBuilder.show();

			} else {
				finish();
			}
		}
		return false;
	}

	/**
	 * 版本更新一键调用,解决一切后顾之忧
	 */
	public void getVersion(Context context) {
		try {
			new NewVersion(context, downloadPath, appVsrsion)
					.checkUpdateVersion();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 百度定位（即开即关）
	 */
	private void locading() {
		BaiduLocationManager.init(getApplicationContext());
		manager = BaiduLocationManager.getInstance();
		manager.setLocationAddCallBack(new LocationStrAddCallBack() {

			@Override
			public void locationStrAdd(String province, String city,
					String district, String street) {
				// 上传定位结果
				if (MethodUtils.isEmpty(province) || MethodUtils.isEmpty(city)
						|| MethodUtils.isEmpty(district)
						|| MethodUtils.isEmpty(street)) {
					manager.stopLocation();
					return;
				}
				ProtocolService.putLocation(
						PhoneInfoUtils.getIMEI(getApplicationContext()),
						province, city, district, street,
						new RequestCallBack<String>() {
							@Override
							public void onSuccess(ResponseInfo<String> arg0) {
								System.out.println();
							}

							@Override
							public void onFailure(HttpException arg0,
									String arg1) {
							}
						});
				// 关闭定位功能
				manager.stopLocation();
			}
		});
		// 开启定位功能
		manager.startLocation();
	}

}